// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.weblayer_private;

import android.content.Intent;
import android.os.RemoteException;
import android.util.AndroidRuntimeException;

/** A utility class for creating and handling common intents. */
public class IntentUtils {
    private static final String sExtraTabId = "TAB_ID";
    private static final String sActivateTabAction =
            "org.chromium.weblayer.intent_utils.ACTIVATE_TAB";

    /**
     * Handles an intent generated by this class.
     * @return true if the intent was handled, or false if the intent wasn't generated by this
     *         class.
     */
    public static boolean handleIntent(Intent intent) {
        if (!intent.getAction().equals(sActivateTabAction)) return false;

        int tabId = intent.getIntExtra(sExtraTabId, -1);
        TabImpl tab = TabImpl.getTabById(tabId);
        if (tab == null) return true;

        try {
            tab.getClient().bringTabToFront();
        } catch (RemoteException e) {
            throw new AndroidRuntimeException(e);
        }
        return true;
    }

    /**
     * Creates an intent to bring a tab to the foreground.
     * This intent should also bring the app to the foreground.
     * @param tabId the identifier for the tab.
     */
    public static Intent createBringTabToFrontIntent(int tabId) {
        Intent intent = WebLayerImpl.createIntent();
        intent.putExtra(sExtraTabId, tabId);
        intent.setAction(sActivateTabAction);
        return intent;
    }
};
